using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;

namespace SmartLauncher
{
	/// <summary>
	/// The MRU list manages a list of the 10 most recent files used. This list is 
	/// then used at many places: 
	/// - "File" menu on the main form
	/// - Toolbar on the mainform
	/// - Pop-up menu of the system tray icon
	/// </summary>
	class MruList
	{
		private List<MruItem> items;

		#region "Constructors & Destructors"
		public MruList()
		{
			items = new List<MruItem>();
			LoadList();
		}
		#endregion

		#region "Disk Access Methods"
		private void LoadList()
		{
			DataTable dt;
			string content;
			MemoryStream ms;
			int i = 0;

			dt = BuildTable();
			content = Properties.Settings.Default.MruList;
			if ((content != null) && (content.Length > 0))
			{
				ms = new MemoryStream(System.Text.ASCIIEncoding.Default.GetBytes(content));
				dt.ReadXml(ms);
			}

			foreach (DataRow dr in dt.Rows)
				if (i < 10)
					if (File.Exists(dr["Filepath"].ToString()) == true)
					{
						items.Add(new MruItem(dr["Filename"].ToString(), dr["Filepath"].ToString()));
						i++;
					}
		}

		private void SaveList()
		{
			DataTable dt;
			MemoryStream ms;
			string content;

			dt = BuildTable();

			foreach (MruItem item in items)
				dt.Rows.Add(item.Filename, item.Filepath);

			ms = new MemoryStream();
			dt.WriteXml(ms);
			content = System.Text.ASCIIEncoding.Default.GetString(ms.GetBuffer());
			Properties.Settings.Default.MruList = content;
			Properties.Settings.Default.Save();
		}
		#endregion

		#region "Memory Access Methods"
		public void Add(string name, string path)
		{
			MruItem foundItem = null;

			path = path.ToLower();
			foreach (MruItem item in items)
				if (item.Filepath == path)
					foundItem = item;

			if (foundItem == null)
				foundItem = new MruItem(name, path);
			else
			{
				foundItem.Filename = name;
				items.Remove(foundItem);
			}

			items.Insert(0, foundItem);
			while (items.Count > 10)
				items.RemoveAt(10);

			SaveList();
		}

		public void Remove(string path)
		{
			int i = 0;
			MruItem item;

			path = path.ToLower();
			while (i < items.Count)
			{
				item = items[i];
				if (item.Filepath.ToLower() == path)
					items.RemoveAt(i);
				else
					i++;
			}
		}
		#endregion

		#region "Internal Functions"
		/// <summary>
		/// Creates the datatable structure that will host the MRU list
		/// </summary>
		/// <returns></returns>
		private DataTable BuildTable()
		{
			DataTable rc = new DataTable("MruList");

			rc.Columns.Add("Filename");
			rc.Columns.Add("Filepath");

			return rc;
		}
		#endregion

		public List<MruItem> Items
		{
			get { return items; }
		}
	}
}
